#!/bin/python
#coding=utf8
import MySQLdb
import datetime
from hynmath import loadConfig

# 设定报警阀值
DELAY_LOG = 3 # 日志到位比当前日期晚3天, 发出警告;
DELAY_CAL = 3 # 智能推荐系统日志计算到的日期, 比日志到达日期晚3天, 发出警告;
DELAY_BMM = 3 # 后台管理系统日志计算到的日期, 比日志到达日期晚3天, 发出警告.
today = datetime.datetime.today()
config = {}
loadConfig(config,'config.txt')

# 检查两个日期是否需要报警
def isDelay(date1, date2, delay):
    warning = ''
    if date1 == None or date2 == None:
        return warning

    delta = (date1-date2).days
    if delta >= delay:
        warning = 'bgcolor="red"'

    return warning

# 创建数据库连接
connection = MySQLdb.connect(host=config['host'], user=config['user'], passwd=config['password'], db=config['database'], init_command=config['encoding'])
cursor = connection.cursor()



# 生成 HTML 邮件内容
fp = open('mailcontent.html', 'wb')
fp.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">')
fp.write('<html>\r\n')
fp.write('<head>\r\n')
fp.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\r\n')
fp.write('</head>\r\n')
#################################################################
#fp.write('<h3>订购首映、看大片的单片和包月的日报</h3>')
#fp.write('<table border="1">\r\n')
#fp.write('<tr align="center"><th>开始时间</th><th>结束时间</th><th>分组</th><th>类别</th><th>类型</th><th>记录条数</th><th>总费用</th></tr>\r\n')
#sql = "call sp_CalcOrderReport('%s',1)" % (config['startDate'])
#cursor.execute(sql)
#sql = "select StartTime,EndTime,ABGroup,Class,Type,Count,Fee from ksdailyreport"
#cursor.execute(sql)
#rows = cursor.fetchall()
#template = '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\r\n'
#for row in rows: 
#    row_str = template % (row[0], row[1], row[2], row[3], row[4], row[5], row[6])
#
#    fp.write(row_str)
#fp.write('</table>\r\n')
#################################################################
fp.write('<body>\r\n')
fp.write('<h3>日志到位及处理情况的日报</h3>')
fp.write('<table border="1">\r\n')
fp.write('<tr align="center"><th>编号</th><td>监控日期</th><th>驻地名称</th><th>日志类型</th><th>日志到位情况</th><th>推荐计算情况</th><th>后台计算情况</th></tr>\r\n')
sql = "select ID,UPTIME,STATION,LOGTYPE,LOGDATE,RECDATE,BMMDATE from mdailyreport"
cursor.execute(sql)
rows = cursor.fetchall()
template = '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td %s>%s</td><td %s>%s</td><td %s>%s</td></tr>\r\n'
for row in rows: 
    row_str = template % (row[0], row[1], row[2], row[3],
                isDelay(today, row[4],DELAY_LOG), row[4],
                isDelay(row[4],row[5],DELAY_CAL), row[5],
                isDelay(row[4],row[6],DELAY_BMM), row[6]
    ) 

    fp.write(row_str)
fp.write('</table>\r\n')
#################################################################
fp.write('*后台管理系统计算详情参见 http://10.61.2.178:8080/BMM</br>\r\n')
fp.write('*该邮件为自动发送, 请误直接答复!\r\n')
fp.write('</body>\r\n')
fp.write('</html>\r\n')
fp.close()
